package com.swipemaster.dialogs;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.swipemaster.R;
import com.swipemaster.common.Const;
import com.swipemaster.network.task.SubmitRecordTask;
import com.swipemaster.record.RecordId;
import com.swipemaster.record.RecordsManager;

public class EntryTextDialog extends Dialog
{
	public EntryTextDialog(final Activity activity, final RecordId recordId)
	{
		super(activity);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.entry_dialog);

		// Removes border of the dialog.
		getWindow().setBackgroundDrawableResource(android.R.color.transparent);
		getWindow().getAttributes().windowAnimations = R.style.DialogAnimationScale;

		final EditText editText = (EditText) findViewById(R.id.entry_dialog_entry);
		editText.setFilters(new InputFilter[]
		{ new InputFilter.LengthFilter(Const.MAX_NAME_LENGTH) });
		editText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
		editText.setText(RecordsManager.getRecords().username);

		final Button exitBtn = (Button) findViewById(R.id.entry_dialog_exit_btn);
		exitBtn.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				dismiss();
			}
		});

		final Button sendBtn = (Button) findViewById(R.id.entry_dialog_send_btn);
		sendBtn.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				final String username = editText.getText().toString();
				if (!TextUtils.isGraphic(username) || TextUtils.isEmpty(username))
				{
					Toast.makeText(activity, R.string.enter_at_least, Toast.LENGTH_SHORT).show();
					return;
				}
				RecordsManager.getRecords().username = username;
				new SubmitRecordTask(activity, RecordsManager.getRecord(recordId), username).execute();
				hideKeyboard(activity, editText);
				dismiss();
			}
		});

		Dialogs.ensureSize(findViewById(R.id.entry_dialog_root_layout));
	}

	private void hideKeyboard(Activity activity, EditText editText)
	{
		final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
	}
}
